import { constantRoutes } from '@/router'
import { getRouters } from '@/api/menu'
import Layout from '@/layout'

const permission = {
  state: {
    routes: [],
    addRoutes: []
  },
  mutations: {
    SET_ROUTES: (state, routes) => {
      state.addRoutes = routes
      state.routes = constantRoutes.concat(routes)
    }
  },
  actions: {
    // 生成路由
    GenerateRoutes({ commit }) {
      return new Promise(resolve => {
        // 向后端请求路由数据
        getRouters().then(res => {
          const accessedRoutes = filterAsyncRouter(res.data)
          console.log(accessedRoutes)
          commit('SET_ROUTES', accessedRoutes)
          resolve(accessedRoutes)
        })
      })
    }
  }
}

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(routes) {
 
  const res = []

  routes.forEach(route => {

    const tmp = { ...route }

    if (!tmp.children) {
      tmp.children = []
    }

    if (tmp.component) {
      // Layout组件特殊处理
      if (tmp.component === 'Layout') {
        tmp.component = Layout
      } else {
        tmp.component = loadView(tmp.component)
      }
    }
      if (tmp.children) {
        tmp.children = filterAsyncRouter(tmp.children)
      }
      res.push(tmp)
  })

  return res
}

export const loadView = (view) => {
  return (resolve) => require([`@/views/${view}`], resolve)
}
export default permission
